package com.cursor.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void run(String... args) throws Exception {
        // 检查表是否存在，不存在则创建
        createTablesIfNotExist();
        // 检查列是否存在，不存在则添加
        addColumnsIfNotExist();
    }
    
    private void createTablesIfNotExist() {
        // 创建license_key表
        jdbcTemplate.execute(
            "CREATE TABLE IF NOT EXISTS license_key (" +
            "id INTEGER PRIMARY KEY AUTOINCREMENT," +
            "license_key VARCHAR(255) NOT NULL," +
            "account_type VARCHAR(50) DEFAULT 'Standard'," +
            "activation_status INTEGER DEFAULT 0," +
            "activation_date TIMESTAMP," +
            "expiry_date TIMESTAMP," +
            "valid_days INTEGER DEFAULT 30," +
            "cursor_pool_usage_total INTEGER DEFAULT 1000," +
            "cursor_pool_usage_used INTEGER DEFAULT 0" +
            ")"
        );
        
        // 创建其他必要的表...
    }
    
    private void addColumnsIfNotExist() {
        // 检查cursor_pool_usage_total列是否存在
        try {
            jdbcTemplate.queryForObject(
                "SELECT cursor_pool_usage_total FROM license_key LIMIT 1", 
                Integer.class
            );
        } catch (Exception e) {
            // 列不存在，使用临时表方法添加列
            jdbcTemplate.execute(
                "CREATE TABLE license_key_temp AS SELECT * FROM license_key;" +
                "DROP TABLE license_key;" +
                "CREATE TABLE license_key (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT," +
                "license_key VARCHAR(255) NOT NULL," +
                "account_type VARCHAR(50) DEFAULT 'Standard'," +
                "activation_status INTEGER DEFAULT 0," +
                "activation_date TIMESTAMP," +
                "expiry_date TIMESTAMP," +
                "valid_days INTEGER DEFAULT 30," +
                "cursor_pool_usage_total INTEGER DEFAULT 1000," +
                "cursor_pool_usage_used INTEGER DEFAULT 0" +
                ");" +
                "INSERT INTO license_key SELECT id, license_key, account_type, activation_status, " +
                "activation_date, expiry_date, valid_days, 1000, 0 FROM license_key_temp;" +
                "DROP TABLE license_key_temp;"
            );
        }
        
        // 检查cursor_pool_usage_used列...类似上面的代码
    }
} 